package com.wechart.utils;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.IOException;
import java.util.List;

/**
 * Created by silenceholic on 2017/5/8.
 */
public abstract class CsvWriter {

    //CSV文件分隔符
    private static final String NEW_LINE_SEPARATOR = "\n";

    private static CSVPrinter csvpriter;

    private static StringBuffer stringBuffer;

    public static byte[] print(List value) throws IOException {
        if (value.size() > 0) {
            return print((String[]) ReflectUtil.getFieldHeaders(value.get(0)), value);
        } else {
            return new byte[0];
        }

    }

    public static byte[] print(String[] csvHeader, List value) throws IOException {
        try {
            stringBuffer = new StringBuffer();
            csvpriter = new CSVPrinter(stringBuffer,
                    CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));

            //获取header
            csvpriter.printRecord(csvHeader);

            for (Object item : value) {
                Object[] v = ReflectUtil.getFieldValues(item);
                csvpriter.printRecord(v);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (csvpriter != null) {
                try {
                    csvpriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuffer.toString().getBytes("GB2312");
//        return stringBuffer.toString().getBytes("utf-8");
    }

    /**
     * 由外部指定 header和object
     * @param csvHeader
     * @param value
     * @return
     * @throws IOException
     */
    public static byte[] printWithObject(String[] csvHeader, List<List<Object>> value) throws IOException {
        try {
            stringBuffer = new StringBuffer();
            csvpriter = new CSVPrinter(stringBuffer, CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));

            //获取header
            csvpriter.printRecord(csvHeader);

            for (List<Object> item : value) {
                csvpriter.printRecord(item);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (csvpriter != null) {
                try {
                    csvpriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuffer.toString().getBytes("GB2312");
    }
}
